package com.hzit.listener;

import javax.servlet.*;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import java.io.*;

@WebListener
public class ApplicationListener implements ServletContextListener, ServletRequestListener {


    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext application = sce.getServletContext();
        System.out.println("当服务器启动的创建application对象，此时调用！整个服务器只调用一次。准备工作...");

        //加载 之前存储的数据
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader("f://data.txt"));
            String count = bufferedReader.readLine().trim();

            application.setAttribute("PAGE_COUNT_EMP_ALL", count);


        } catch (Exception e) {
            System.out.println("配置浏览量文件不存在....");
            e.printStackTrace();
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

        Object count = sce.getServletContext().getAttribute("PAGE_COUNT_EMP_ALL");

        System.out.println("服务器关闭之前....一般用来：释放资源，遗言");

        //挂掉之前 把 浏览记录持久化(数据库,xx.txt)
        File file = new File("f://data.txt");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            FileWriter fileWriter = new FileWriter(file);

            fileWriter.write(count + "");
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * Servlet监听器-销毁
     *
     * @param sre
     */
    @Override
    public void requestDestroyed(ServletRequestEvent sre) {

    }

    /**
     * Servlet监听器-创建
     *
     * @param sre
     */
    @Override
    public void requestInitialized(ServletRequestEvent sre) {

        Object c = sre.getServletContext().getAttribute("PAGE_COUNT_EMP_ALL");
        int count = (c == null || c.equals("")) ? 0 : Integer.parseInt(c.toString());
        ///emp/all
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();

        String servletPath = request.getServletPath();
        if ("/emp/all".equals(servletPath)) {

            //count++;

            ServletContext application = request.getServletContext();
            application.setAttribute("PAGE_COUNT_EMP_ALL", ++count);
        }


    }
}
